<template>
  <div class="content">
    <admin-menu/>
    <main class="ml-64 flex-1 p-6 bg-gray-100 min-h-screen">
      <el-card shadow="never" style="margin-bottom: 10px">
        <header class="flex justify-between items-center mb-6">
          <div>
            <h1 class="text-3xl font-bold text-gray-800">岗位管理中心</h1>
            <p class="text-sm text-gray-500 mt-1">待审核岗位数：
              {{ filteredPositions.filter(item => item.QYDM === 1).length }} 个</p>
          </div>
          <div class="flex items-center space-x-4">
            <el-button icon="el-icon-plus" type="text" @click="addGw">审核通过</el-button>
            <el-button icon="el-icon-plus" type="text" @click="addGw">发布新岗位</el-button>
            <el-button icon="el-icon-edit" type="text" @click="eiditGw">编辑岗位</el-button>
            <el-button icon="el-icon-search" type="text" @click="lookGw">查看岗位详情</el-button>
            <el-dropdown trigger="click">
              <el-button icon="el-icon-download"></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>导出当前列表</el-dropdown-item>
                  <el-dropdown-item>导出全部数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </header>
      </el-card>


      <!-- 岗位管理表格 -->
      <el-card class="main-table" shadow="never">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="flex items-center space-x-4">
              <el-input
                  v-model="searchKey"
                  clearable
                  placeholder="搜索岗位名称/编号"
                  style="width: 240px">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
              <el-select
                  v-model="filterStatus"
                  clearable
                  placeholder="状态筛选"
                  style="width: 120px">
                <i slot="prefix" class="el-input__icon el-icon-refresh"></i>
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <el-date-picker
                  v-model="dateRange"
                  end-placeholder="结束日期"
                  range-separator="至"
                  start-placeholder="开始日期"
                  type="daterange">
              </el-date-picker>
            </div>
            <div class="flex items-center space-x-2">
              <el-button type="text" @click="toggleAdvancedSearch">
                高级筛选 <i :class="advancedSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </el-button>
              <el-button icon="el-icon-refresh"></el-button>
            </div>
          </div>
        </template>

        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="paginatedPositions"
            :row-class-name="tableRowClassName"
            border
            element-loading-background="rgba(255, 255, 255, 0.8)"
            element-loading-spinner="el-icon-loading"
            element-loading-text="加载中..." highlight-current-row stripe
            style="width: 100%"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
            @current-change="handleCurrentChangeTable">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="不通过原因" prop="YY" width="160" fixed="left">
            <template #default="scope">
              <span v-if="scope.row.YY === ''">暂无原因</span>
              <span v-else class="text-danger">{{ scope.row.YY }}</span>
            </template>
          </el-table-column>
          <el-table-column label="岗位ID" prop="ID" width="100"></el-table-column>
          <el-table-column :formatter="formatText" label="岗位名称" prop="GWMC" width="120"></el-table-column>
          <!--          <el-table-column :formatter="formatText" label="岗位描述" prop="GWMS" width="180"></el-table-column>
                    <el-table-column :formatter="formatText" label="岗位要求" prop="GWYQ" width="180"></el-table-column>-->
          <el-table-column label="岗位分类" prop="FLMC" width="100"></el-table-column>
          <el-table-column :width="180" label="岗位发布时间" prop="FBSJ" sortable>
            <template #default="scope">
              {{ fbsjToDate(scope.row.FBSJ) }}
            </template>
          </el-table-column>
          <!--          <el-table-column :formatter="formatText" label="投递说明" prop="TDSM"></el-table-column>-->
          <el-table-column :formatter="(row) => row.ZGXZ + '元/月'" label="最高薪资" prop="ZGXZ" sortable
                           width="100"></el-table-column>
          <el-table-column :formatter="(row) => row.ZDXZ + '元/月'" label="最低薪资" prop="ZDXZ" sortable
                           width="100"></el-table-column>
          <el-table-column label="最低学历要求" prop="ZDXLYQ"/>
          <el-table-column :formatter="formatText" label="工作地点" prop="GZDD"></el-table-column>
          <el-table-column label="工作省份" prop="SFMC"/>
          <el-table-column label="实习标志" prop="SXBZ">
            <template #default="scope">
              {{ scope.row.SXBZ === 1 ? "实习岗位" : "正式岗位" }}
            </template>
          </el-table-column>
          <el-table-column :formatter="formatText" label="专业限制" prop="ZYXZ"></el-table-column>
          <el-table-column :formatter="formatText" label="单位名称" prop="DWMC"></el-table-column>
          <el-table-column :formatter="formatText" label="投递次数" prop="TDCS"></el-table-column>
          <el-table-column :formatter="formatText" label="招聘人数" prop="ZPRS"></el-table-column>
          <el-table-column fixed="left" label="启用状态">
            <template #default="scope">
                <span>
                  <i
                      :class="scope.row.QYDM === 1 ? 'el-icon-check' : 'el-icon-close'"
                      :style="{ color: scope.row.QYDM === 1 ? 'green' : 'red', marginRight: '5px' }"
                  ></i>
                  {{ scope.row.QYDM === 1 ? "启用" : "关闭" }}
                </span>
            </template>
          </el-table-column>


          <el-table-column align="right" fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button size="mini" @click="ShowJobDetail(scope.row)">岗位详情</el-button>
              <el-button size="mini" type="success" @click="CxSh(scope.row)">撤销审核</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="flex justify-between items-center mt-4">
          <div>
            <el-button size="mini" @click="batchOffline">批量审核不通过</el-button>
            <el-button size="mini">批量审核通过</el-button>
          </div>

          <el-pagination
              :current-page.sync="currentPage"
              :page-size.sync="pageSize"
              :page-sizes="[ 5, 7, 9,11 , 13]"
              :total="total"
              background
              layout="total, sizes, prev, pager, next"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange">
          </el-pagination>
        </div>

      </el-card>
    </main>
  </div>
</template>

<script>
import ECharts from 'vue-echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/pie';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/legend';
import axios from "axios";
import AdminMenu from "@/components/admin/Admin_menu.vue";

export default {
  components: {AdminMenu, ECharts},
  name: 'DwJob',
  data() {
    return {
      loading: false,
      hotPositions: [
        {name: '高级前端工程师', count: 235},
        {name: '产品经理', count: 189},
        {name: 'UI设计师', count: 156}
      ],
      searchKey: '',
      filterStatus: null, // 状态筛选
      dateRange: [],
      advancedSearch: false,
      selectedPosition: null,
      drawerVisible: false,
      currentPage: 1,
      pageSize: 5, // 更新每页显示条数为 5
      total: 0,
      paginatedData: [],
      statusOptions: [
        {value: 1, label: '启用'},
        {value: 0, label: '禁用/下线'},
        {value: 3, label: '已投递满'}
      ],
      YY: "",// 审核不通过的原因
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      // 当前选中岗位数据
      currentJobSelectRow: null,
      selectedRows: [],// 批量操作选中的行
    };
  },
  computed: {
    filteredPositions() {
      return this.paginatedData.filter(item => {
        return (
            (!this.searchKey || item.gwmc.includes(this.searchKey)) &&
            (!this.filterStatus || (item.qydm === this.filterStatus))
        );
      });
    },
    paginatedPositions() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredPositions.slice(start, end);
    }
  },
  mounted() {
    this.getLoginUserInfo();// 获取登录用户信息
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    //撤销审核1、删除GWQSK数据 2、新增消息给XXDMK
    CxSh(Job) {
      $.confirm({
        title: '⚠️ 提示',
        content: '确认撤销审核该岗位吗？',
        type: 'orange',
        animation: 'zoom',
        closeAnimation: 'scale',
        animateFromElement: false,
        backgroundDismissAnimation: 'glow',
        boxWidth: '400px',
        useBootstrap: false,
        theme: 'modern',
        onOpenBefore: function () {
          setTimeout(() => {
            $('.jconfirm').css('z-index', 99999);
          }, 0);
        },
        buttons: {
          确定: {
            text: '✅ 确定撤销',
            btnClass: 'btn-orange',
            action: () => {
              // 第一步：删除 GWQSK 表中的记录
              const deleteForm = new FormData();
              deleteForm.append('gwdm', Job.ID);  // Job.ID 即岗位ID

              axios.post('/dataGwdmk/deleteGwqs', deleteForm)
                  .then(res => {
                    if (res.data.result) {
                      // 第二步：插入消息到 XXDMK 表
                      /*
                      CFZ	触发者
                      CFZXW	触发者行为
                      JSZ	接收者
                      DZLX	动作类型:
                      CFZSFDM	触发者身份代码
                      JSZSFDM	接收者身份代码
                      DZNR	动作内容*/
                      const msgForm = new FormData();
                      msgForm.append('cfz', this.UserInfo.username);
                      msgForm.append('cfzxw', "岗位审核不通过撤销");
                      msgForm.append('jsz', Job.FBZ);
                      msgForm.append('dzlx', 19);
                      msgForm.append('cfzsfdm', 1);
                      msgForm.append('jszsfdm', Job.FBZYHSFDM);
                      msgForm.append('dznr', `岗位【${Job.GWMC}】已被${this.UserInfo.name}撤销审核不通过`);

                      return axios.post('/xxdmk/addXxdmk', msgForm);
                    } else {
                      throw new Error(res.data.msg || '撤销失败');
                    }
                  })
                  .then(msgRes => {
                    if (msgRes.data.result) {
                      this.$message.success('撤销审核成功，并已通知相关用户');
                      this.getAllJob();  // 刷新岗位列表
                    } else {
                      this.$message.error('撤销成功，但发送消息失败：' + msgRes.data.msg);
                    }
                  })
                  .catch(err => {
                    this.$message.error('撤销失败：' + err.message);
                  });

              //return false; // 阻止默认关闭动画直到处理完成
            }
          },
          取消: {
            text: '❎ 取消',
            btnClass: 'btn-default'
          }
        }
      });
    },
    // 弹出重试确认弹窗
    retryConfirm(msg, row) {
      const vm = this;
      $.confirm({
        title: '修改失败',
        content: `错误信息：${msg}<br><br>是否重试？`,
        buttons: {
          重试: {
            btnClass: 'btn-red',
            action: () => {
              vm.PublishJobNotPass(row);
            }
          },
          取消: {
            text: '❎ 取消',
            action: () => {
              vm.$message.info('已取消重试');
            }
          }
        }
      });
    },
    // 审核通过
    PublishJob(row) {
      $.confirm({
        title: '⚠️ 提示',
        content: '确认通过该岗位吗？',
        type: 'orange',
        animation: 'zoom',
        closeAnimation: 'scale',
        animateFromElement: false,
        backgroundDismissAnimation: 'glow',
        boxWidth: '400px',
        useBootstrap: false,
        theme: 'modern',
        onOpenBefore: function () {
          setTimeout(() => {
            // ✅ 只设置弹窗本体 z-index，避免被背景遮罩盖住
            $('.jconfirm').css('z-index', 99999);
            // ❌ 不设置 .jconfirm-bg 的 z-index
          }, 0);
        },
        buttons: {
          确定: {
            text: '✅ 确定',
            btnClass: 'btn-orange',
            action: () => {
              let SHDATA = new FormData();
              SHDATA.append('id', row.ID);
              SHDATA.append('shbz', 1);
              axios.post("/dataGwdmk/updateGangWei", SHDATA).then(res => {
                if (res.data.result) {
                  this.$message.success("岗位审核通过成功！");
                  this.getAllJob();
                } else {
                  this.$message.error("岗位审核通过失败:" + res.data.msg);
                }
              }).catch(err => {
                this.$message.error("岗位审核通过失败:" + err.message);
              });
            }
          },
          取消: {
            text: '❌ 取消',
            action: () => {
              console.log("用户点击了取消");
            }
          }
        }
      });
    },
    fbsjToDate(fbsj) {
      return new Date(fbsj).toLocaleDateString()
    },
    // 查看岗位详情
    lookGw() {
      // 获取当前行数据
      if (this.currentJobSelectRow === null) {
        //使用 Jquery confirm 弹窗提示
        this.currentJobSelectRow = null;
        this.$confirm('请选择需要查看的岗位！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('确定');
        }).catch(() => {
          console.log('取消');
        });
      } else {
        console.log("跳转到岗位详情页面");
        console.log(this.currentJobSelectRow.id);
        this.$router.push({path: '/dw/jobDetail', query: {id: this.currentJobSelectRow.id}})
      }

    },
    // 编辑岗位
    eiditGw() {
      // 获取当前行数据
      if (this.currentJobSelectRow === null) {
        $.confirm({
          title: '提示',
          content: '请选择需要编辑的岗位！',
          type: 'orange', // warning 样式
          buttons: {
            确定: {
              btnClass: 'btn-orange',
              action: () => {
                console.log("用户点击了确定");
                // 这里可以执行编辑操作
              }
            },
            取消: () => {
              console.log("用户点击了取消");
            }
          }
        });
      } else {
        console.log("跳转到编辑岗位页面");
        console.log(this.currentJobSelectRow.id);
        this.$router.push({path: '/dw/DwJobEditView', query: {id: this.currentJobSelectRow.id}})
      }
    },
    // 高级筛选
    toggleAdvancedSearch() {
    },
    // 前往编辑岗位页面
    addGw() {
      this.$router.push('/dw/addJob');
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        // console.log("渲染第一行样式！！！");
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    async getLoginUserInfo() {
      try {
        this.loading = true;
        const response = await axios.get('/user/checkSession');
        if (!response.data.result) {
          this.$message.error("获取用户信息失败，请重新登录！");
        } else {
          this.UserInfo = {
            name: response.data.name,
            role: response.data.role,
            username: response.data.username
          };
          this.getAllJob();
        }
      } catch (error) {
        this.$message.error("获取用户信息失败，请重新登录！");
      }
    },
    getAllJob() {
      this.loading = true;
      axios.get(`/dataGwdmk/getPassJopData?YHM=${this.UserInfo.username}&YHSFDM=${1}`).then(res => {
        if (res.data.result) {
          this.paginatedData = res.data.data;
          this.total = this.filteredPositions.length; // 设置总数
        } else {
          this.$message.error("获取岗位数据失败！，后台错误");
        }
        this.loading = false;
      }).catch(err => {
        this.loading = false;
        this.$message.error("获取岗位数据失败！，网络错误");
      });
    },
    openPositionDialog() {
      // 打开新建岗位对话框
    },
    batchOffline() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要操作的岗位！");
        return;
      }

      const vm = this;

      // 第一步：弹窗填写原因
      $.confirm({
        title: '填写原因',
        content: `<input type="text" id="newVal" class="form-control" placeholder="请输入不通过原因"/>`,
        boxWidth: '400px',
        useBootstrap: false,
        theme: 'modern',
        onOpen: () => {
          setTimeout(() => {
            $('.jconfirm').css('z-index', 99999);
          }, 0);
        },
        buttons: {
          确定: {
            text: '✅ 确定',
            btnClass: 'btn-blue',
            action: () => {
              const inputVal = $('#newVal').val().trim();
              if (!inputVal) {
                vm.$message.warning('请输入原因');
                return false; // 阻止关闭
              }

              vm.YY = inputVal;

              // 第二步：确认下线
              $.confirm({
                title: '⚠️ 确认下线',
                content: `确定要审核不通过选中的 ${vm.selectedRows.length} 个岗位吗？`,
                type: 'orange',
                buttons: {
                  确定: {
                    text: '下线',
                    btnClass: 'btn-orange',
                    action: () => {
                      const requests = vm.selectedRows.map(row => {
                        const formData = new FormData();
                        formData.append('gwdm', row.ID);
                        formData.append('yy', vm.YY);
                        return axios.post("/dataGwdmk/insertGwqs", formData);
                      });

                      Promise.all(requests)
                          .then(() => {
                            vm.$message.success("批量操作成功！");
                            vm.getAllJob();
                          })
                          .catch(err => {
                            vm.$message.error("批量操作失败：" + err.message);
                          });
                    }
                  },
                  取消: {
                    text: '取消',
                    btnClass: 'btn-default'
                  }
                }
              });
              return true; // 关闭第一个弹窗
            }
          },
          取消: {
            text: '❎ 取消',
            action: () => {
              vm.$message.info('操作已取消');
            }
          }
        }
      });
    },
    // 选中行修改事件
    handleCurrentChangeTable(currentRow) {
      /*  console.log("当前选中行：", currentRow);*/
      this.currentJobSelectRow = currentRow;
    },
    formatText(row, column, cellValue) {
      return cellValue.length > 25 ? cellValue.slice(0, 10) + '...' : cellValue;
    },

    ShowJobDetail(row) {
      // 查看岗位详情逻辑
      console.log("跳转到岗位详情页面");
      this.$router.push({path: '/dw/jobDetail', query: {id: row.id}})
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置到第一页
    },
  }
}
</script>

<style scoped>

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.p-6 {
  padding: 10px !important;
}

.hover-effect {
  @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
}

.stat-card {
  @apply h-40 flex flex-col justify-between;
}

.chart-card {
  @apply border-0 bg-white rounded-lg shadow-sm;
}

.card-title {
  @apply text-lg font-semibold text-gray-800;
}

.status-tag {
  @apply px-3 py-1 rounded-full;
}

.advanced-search {
  @apply bg-gray-50 p-4 rounded;
}

.main-table {
  @apply border-0 shadow-lg;
}

:deep(.el-card__header) {
  @apply border-b-0 bg-gray-50;
}

.mb-6 {
  margin-bottom: 0.5rem !important;
}
</style>